package com.zzyl.intercept;

import com.zzyl.constant.Constants;
import com.zzyl.enums.BasicEnum;
import com.zzyl.exception.BaseException;
import com.zzyl.properties.JwtProperties;
import com.zzyl.utils.JwtUtil;
import com.zzyl.utils.UserThreadLocal;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
@Slf4j
public class WechatUserIntercept implements HandlerInterceptor {

    @Autowired
    private JwtProperties jwt;

    /**
     * 获取token 获取userid 放入ThreadLocal
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 获取请求路径
        String requestURI = request.getRequestURI();
        // 判断是否登录，就放行
        if (requestURI.contains("login")) {
            return true;
        }
        // 从头中获取key 获取token
        String token = request.getHeader("authorization");
        if (token == null) {
            log.info("token为空");
            throw new BaseException(BasicEnum.LOGIN_LOSE_EFFICACY);
        }
        // 解析token，获取userid
        Claims claims = JwtUtil.parseJWT(jwt.getBase64EncodedSecretKey(), token);

        // 把uesrid放到threadlocal中
        UserThreadLocal.set(Long.parseLong(claims.get(Constants.JWT_USERID).toString()));
        UserThreadLocal.setSubject(claims.get(Constants.JWT_USERNAME).toString());
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserThreadLocal.remove();
        UserThreadLocal.removeSubject();
    }
}
